from django.conf import settings

# 创建路由 DATABASE_ROUTERS
DATABASE_ROUTERS = ['django_tenants.routers.TenantSyncRouter', ] + list(getattr(settings, 'DATABASE_ROUTERS', []))
DATABASE_ROUTERS = sorted(list(set(DATABASE_ROUTERS)), key=DATABASE_ROUTERS.index)
# 中间件
MIDDLEWARE = ['django_tenants.middleware.main.TenantMainMiddleware', ] + list(getattr(settings, 'MIDDLEWARE', []))
MIDDLEWARE = sorted(list(set(MIDDLEWARE)), key=MIDDLEWARE.index)

# SHARED_APPS
SHARED_APPS = [
                  'django_tenants',
                  'django.contrib.auth',
                  'django.contrib.sessions',
                  'django.contrib.messages',
                  'django.contrib.staticfiles',
                  'plugins.dvadmin_tenant_backend',
                  'django.contrib.contenttypes',
                  'dvadmin.system',
                  'captcha'
              ] + list(getattr(settings, 'SHARED_APPS', []))
SHARED_APPS = sorted(list(set(SHARED_APPS)), key=SHARED_APPS.index)

# TENANT_APPS
TENANT_APPS = getattr(settings, 'TENANT_APPS', settings.INSTALLED_APPS)
#
INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS]

# 设置租户和域模型所在的位置
TENANT_MODEL = "dvadmin_tenant_backend.Client"  # app.Model
#
TENANT_DOMAIN_MODEL = "dvadmin_tenant_backend.Domain"  # app.Model

# 日志
LOGGING = settings.LOGGING
LOGGING["filters"] = {
    'tenant_context': {
        '()': 'django_tenants.log.TenantContextFilter'
    }
}
TENANT_LOG_FORMAT = '[%(schema_name)s:%(domain_url)s][%(asctime)s][%(name)s.%(funcName)s():%(lineno)d] [%(levelname)s] %(message)s'
LOGGING["handlers"]["console"]["filters"] = ['tenant_context']
LOGGING["handlers"]["console"]["formatter"] = 'tenant_context'
LOGGING_FORMATTERS = LOGGING["formatters"]
LOGGING_FORMATTERS["tenant_context"] = {
    'format': TENANT_LOG_FORMAT,
    'datefmt': '%Y-%m-%d %H:%M:%S',
}
LOGGING["formatters"] = LOGGING_FORMATTERS
